/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-05-28 09:02:23
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-10-24 14:23:16
 * @FilePath: \express-demo\middleWares\auth\jwt.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const jwt = require('jsonwebtoken');
const secret = process.env.PRIVATE_KEY || "48dd0a48706c77e5e369e7480a600b6776a8078e8a5c4a86b6627d0cd03aff4d";

const blacklistedTokens = new Set();

// 生成 tocken
function generateToken(payload) {
    return jwt.sign(payload, secret, { expiresIn: '1h' });
}
// 校验 tocken
function verifyToken(req, res, next) {
    const author = req.headers.authorization;
    if(!author) return res.status(401).send({ message: '未授权' }); 
    const token = author.split(' ')[1];
    // 校验 token
    if(blacklistedTokens.has(token)) return res.status(401).json({ message: 'token 已失效' });

    jwt.verify(token, secret, (err, user) => {
      if (err) return res.status(403).send({ message: '无效 token' }); // 无效 token
      req.user = user;
      next();
    });
}
// 退出时 清除 token
function destroyToken(req, res) {
    // 从请求头中获取token
    const author = req.headers.authorization;
    if (author) {
        const token = author.split(' ')[1];
        // 将token添加到黑名单
        blacklistedTokens.add(token);
    }
    // 清除cookie中的token
    res.clearCookie('token', { httpOnly: true });
    res.status(200).json({ message: 'Token已成功注销' });
};

module.exports = { generateToken, verifyToken, destroyToken };
